package com.imooc.springmvc3.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器:对所有的请求计算时间
 *   注释:
 *      继承HandlerInterceptorAdapter类来实现自定义拦截器
 * Created by joe on 16-8-12.
 */
public class DemoInterceptor extends HandlerInterceptorAdapter {
    /**
     * 重写 preHandle方法,在请求发生前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime",startTime);
        return true;
    }

    /**
     *重写 postHandle方法,在请求之后执行
     * @param request
     * @param response
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,Object handler, ModelAndView modelAndView) throws Exception{
        long startTime = (Long) request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime = System.currentTimeMillis();
        System.out.println("本次请求处理的时间是: " + new Long(endTime -startTime) + "ms" );
        request.setAttribute("handlingTime",endTime - startTime);
    }
}
